import { defineStore } from 'pinia';
import { getToken, removeToken, setToken } from '../utils/token-utils';
import type { UserInfoState } from './interface';
import { ElMessage } from 'element-plus'
import { allAsyncRoutes, anyRoutes, staticRoutes } from '@/router/routes'
import { getUserInfoApi, loginApi } from '@/api/acl/login';
import type { RouteRecord, RouteRecordRaw } from 'vue-router';
import { cloneDeep } from 'lodash'
import router from '@/router';


/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore('userInfo', {

  state: (): UserInfoState => ({
    token: getToken() as string,
    name: '',
    avatar: '',
    roles: [],
    // 按钮权限相关
    buttons: [],
    // 存储服务器响应回来的路由数组 也就是用户能够访问的路由
    routeNames: [],
    menuRoutes: []
  }),

  actions: {
    async login(username: string, password: string) {
      try {
        const result = await loginApi(username, password)
        // console.log(result)
        setToken(result.token)
        this.token = result.token
      } catch (error) { ElMessage.error('登录失败') }
    },

    async getInfo() {
      const result = await getUserInfoApi()
      // console.log(result)
      this.name = result.name
      this.avatar = result.avatar
      this.roles = result.roles
      this.buttons = result.buttons
      this.routeNames = result.routes
      this.menuRoutes = staticRoutes
      this.setRoutes(result.routes)
      // this.avatar = 
      // return new Promise((resolve, reject) => {
      //   setTimeout(() => {
      //     this.name = 'admin'
      //     this.avatar = 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
      //     this.menuRoutes = staticRoutes
      //     resolve({ name: this.name, avatar: this.avatar, token: this.token })
      //   }, 1000)
      // })
    },

    setRoutes(routeNames: string[]) {
      const asyncRoutes = filterAsyncRoutes(cloneDeep(allAsyncRoutes), routeNames)
      // console.log(asyncRoutes)
      addRoutes(asyncRoutes)
      addRoutes(anyRoutes)
      this.menuRoutes = [...staticRoutes, ...allAsyncRoutes, ...anyRoutes]
    },

    reset() {
      // 删除local中保存的token
      removeToken()
      // 提交重置用户信息的mutation
      this.token = ''
      this.name = ''
      this.avatar = ''
    },
  },
});

// 根据服务器端响应回来的路由名称 过滤对应的异步路由对象
function filterAsyncRoutes(asyncRoutes: RouteRecordRaw[], routeNames: string[]) {
  const newAsyncRoutes = asyncRoutes.filter(routeObj => {
    const name = routeObj.name

    if (!routeNames.includes(name as string)) {
      return false
    }

    if (routeObj.children?.length) {
      routeObj.children = filterAsyncRoutes(routeObj.children, routeNames)
    }
    return true
  })

  // console.log(newAsyncRoutes)
  return newAsyncRoutes

}

//注入路由
function addRoutes(asyncRoutes: RouteRecordRaw[]) {
  asyncRoutes.forEach(routeObj => {
    router.addRoute(routeObj)
  })
}